package com.jmga.ecogasfinder.services;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.w3c.dom.DOMException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.jmga.ecogasfinder.R;
import com.jmga.ecogasfinder.activities.Preferences;
import com.jmga.ecogasfinder.providers.GasFinderProvider;
import com.jmga.ecogasfinder.vo.GasStation;

public class LookupGasFinderService extends Service {

	public static final String NEW_GAS_STATION_FOUND = "NEW_GAS_STATION_FOUND";
	public static final String UPDATE_GAS_STATION_FOUND = "UPDATE_GAS_STATION_FOUND";
	public static final String STARTED_LOADING = "STARTED_LOADING";
	public static final String FINISHED_LOADING = "FINISHED_LOADING";
	public static final String PERIMETER_SEARCH = "PERIMETER_SEARCH";
	public static final String LOOKUP_AREA_METERS = "LOOKUP_AREA_METERS";
	

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(getClass().getName(), "onStartCommand: " + intent.getAction() + "Flags: " + flags + " startId " + startId);
		if ((flags & START_FLAG_RETRY) == 0) {
			// if it's a restart, do something.
		} else {
			// Alternative background process.
		}
		GasStation gasStation = (GasStation) intent.getSerializableExtra(GasFinderProvider.KEY_STATION);
		int gasType = intent.getIntExtra(Preferences.PREF_GAS_TYPE, 1);
		int lookUpAreaMeters = intent.getIntExtra(LookupGasFinderService.LOOKUP_AREA_METERS, 1000);
		
		boolean isFavourite = intent.getBooleanExtra(GasFinderProvider.KEY_FAVOURITE, false);
		Boolean isRegular = intent.getBooleanExtra(GasFinderProvider.KEY_REGULAR, false);
		Boolean isObservable = intent.getBooleanExtra(GasFinderProvider.KEY_OBSERVABLE, false);
		
		String perimeterSearch = intent.getStringExtra(PERIMETER_SEARCH);
		
		Log.d(getClass().getName(), "Perimeter search:" + perimeterSearch);
		
		if(gasStation != null) {
			if(isRegular) {
				saveGasStation(gasStation, isRegular, isObservable);
			} else {
				setFavourite(gasStation, isFavourite);
			}
		} else {
			lookUp(gasType, perimeterSearch, lookUpAreaMeters);
		}

		return START_STICKY;
	}
	
	private void lookUp(int gasType, String perimeterSearch, int lookUpAreaMeters) {
		GasStationLookupTask gasStationLookup = new GasStationLookupTask();
		Object[] parameters = new Object[3];
		parameters[0] = Integer.valueOf(gasType);
		parameters[1] = perimeterSearch;
		parameters[2] = lookUpAreaMeters;
		
		gasStationLookup.execute(parameters);
	}
	
	private void addNewGS(GasStation gasStation, String fuelType, String precio) {
		announceNewGasStation(gasStation);

		ContentResolver cr = getContentResolver();
		
		String wherePrice = GasFinderProvider.KEY_DATE + " = " + gasStation.getDate().getTime();
		wherePrice += " AND " + GasFinderProvider.KEY_GAS_TYPE + " = '" + fuelType + "'";
		wherePrice += " AND " + GasFinderProvider.KEY_STATION + " = '" + gasStation.getXkey() + "'";
		
		Cursor cursor = cr.query(GasFinderProvider.CONTENT_URI_PRICES, null,
				wherePrice, null, null);

		ContentValues values = null;
		
		if (cursor.getCount() == 0) {
			values = new ContentValues();

			values.put(GasFinderProvider.KEY_DATE, gasStation.getDate().getTime());
			values.put(GasFinderProvider.KEY_STATION, gasStation.getXkey());
			values.put(GasFinderProvider.KEY_PRICE, precio);
			values.put(GasFinderProvider.KEY_GAS_TYPE, fuelType);

			cr.insert(GasFinderProvider.CONTENT_URI_PRICES, values);
			Log.d(getClass().getName(), "addNewGS-Data-Inserted:" + gasStation.getXkey() + ":" + precio + ":" + fuelType + ":" + gasStation.getDate().getTime());
		}
		cursor.close();
	}
	
	private void setFavourite(GasStation gasStation, boolean isFavourite) {
		gasStation.setFavourite(isFavourite);
		saveGasStation(gasStation, null, null);
		announceUpdateGasStation(gasStation);
	}
	
	private void saveGasStation(GasStation gasStation, Boolean regular, Boolean observable) {
		ContentResolver cr = getContentResolver();
		
		String whereStation = GasFinderProvider.KEY_X_COORD + " = '" + gasStation.getXCoord() 
			+ "' AND " + GasFinderProvider.KEY_Y_COORD + " = '" + gasStation.getYCoord() + "'";
		ContentValues values = null;

		Cursor cursor = cr.query(GasFinderProvider.CONTENT_URI_STATIONS, null,
				whereStation, null, null);
		
		values = new ContentValues();
		values.put(GasFinderProvider.KEY_XKEY, gasStation.getXkey());
		values.put(GasFinderProvider.KEY_LABEL, gasStation.getLabel());
		values.put(GasFinderProvider.KEY_OPERATOR, gasStation.getOperator());
		values.put(GasFinderProvider.KEY_ADDRESS, gasStation.getAddress());
		values.put(GasFinderProvider.KEY_LANE, gasStation.getLane());
		values.put(GasFinderProvider.KEY_POSTAL_CODE, gasStation.getPostalCode());
		values.put(GasFinderProvider.KEY_PROVINCE, gasStation.getProvincie());
		values.put(GasFinderProvider.KEY_LOCALITY, gasStation.getLocality());
		values.put(GasFinderProvider.KEY_SALE_TYPE,	gasStation.getSaleType());
		values.put(GasFinderProvider.KEY_SENT_TYPE, gasStation.getSentType());
		values.put(GasFinderProvider.KEY_X_COORD, Double.parseDouble(gasStation.getXCoord()));
		values.put(GasFinderProvider.KEY_Y_COORD, Double.parseDouble(gasStation.getYCoord()));
		values.put(GasFinderProvider.KEY_FAVOURITE, Integer.valueOf(gasStation.isFavourite()? 1 : 0));
		values.put(GasFinderProvider.KEY_REGULAR, Integer.valueOf((regular != null && regular)? 1 : 0));
		values.put(GasFinderProvider.KEY_OBSERVABLE, Integer.valueOf((observable != null && observable)? 1 : 0));

		if (cursor.getCount() == 0) {
			cr.insert(GasFinderProvider.CONTENT_URI_STATIONS, values);
			Log.d(getClass().getName(), "saveGasStation-Data-Inserted:" + gasStation.getXkey());
		} else if (cursor.getCount() == 1) {
			cr.update(GasFinderProvider.CONTENT_URI_STATIONS, values, whereStation, null);
			Log.d(getClass().getName(), "saveGasStation-Data-Updated:" + gasStation.getXkey());
		}

		cursor.close();
	}

	private void frequencyUp(String station) {
		ContentResolver cr = getContentResolver();
		
		String whereStation = GasFinderProvider.KEY_STATION + " = '" + station + "' ";
		ContentValues values = null;

		Cursor cursor = cr.query(GasFinderProvider.CONTENT_URI_FREQUENCY, null,
				whereStation, null, null);
		
		values = new ContentValues();
		values.put(GasFinderProvider.KEY_STATION, station);

		if (cursor.getCount() == 0) {
			values.put(GasFinderProvider.KEY_TIMES, 1);
			cr.insert(GasFinderProvider.CONTENT_URI_FREQUENCY, values);
		} else if (cursor.getCount() == 1) {
			cursor.moveToNext();
			int times = cursor.getInt(cursor.getColumnIndexOrThrow(GasFinderProvider.KEY_TIMES));
			times++;
			values.put(GasFinderProvider.KEY_TIMES, times);
			cr.update(GasFinderProvider.CONTENT_URI_FREQUENCY, values, whereStation, null);
		}

		cursor.close();
	}
	
	private void announceNewGasStation(GasStation gasStation) {
		Intent intent = new Intent(NEW_GAS_STATION_FOUND);
		intent.putExtra(GasFinderProvider.KEY_STATION, gasStation);
		
		Log.d(getClass().getName(), "announceNewGasStation-sendBroadcast:" + gasStation.getXkey() + ":" + gasStation.getPrice());
		sendBroadcast(intent);
	}
	
	private void announceUpdateGasStation(GasStation gasStation) {
		Intent intent = new Intent(UPDATE_GAS_STATION_FOUND);
		intent.putExtra(GasFinderProvider.KEY_STATION, gasStation);
		
		Log.d(getClass().getName(), "announceUpdateGasStation-sendBroadcast:" + gasStation.getXkey() + ":" + gasStation.getPrice());
		sendBroadcast(intent);
	}

	private class GasStationLookupTask extends AsyncTask<Object, GasStation, Integer> {
		@Override
		protected synchronized Integer doInBackground(Object... params) {
			URL url;
			
			Intent intentLoading = new Intent(STARTED_LOADING);
			Log.d(getClass().getName(), "sendBroadcast:" + STARTED_LOADING);
			sendBroadcast(intentLoading);
			Integer founds = 0;
			int gasType = (Integer) params[0];
			String perimeterSearch = (String) params[1];
			// int lookUpAreaMeters = (Integer) params[2];
			
			try {
				String gasStationsLookupFeed = getString(R.string.gas_station_feed);
				gasStationsLookupFeed += "&" + getString(R.string.gasTypeParam_feed) +  "=" + gasType;
				gasStationsLookupFeed += "&" + getString(R.string.BBOXParam_feed) +  "=" + perimeterSearch;
				
				url = new URL(gasStationsLookupFeed);
				
				Log.d(getClass().getName(), "START-refreshGSList:" + url.toExternalForm());

				URLConnection connection;
				connection = url.openConnection();

				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				int responseCode = httpConnection.getResponseCode();

				if (responseCode == HttpURLConnection.HTTP_OK) {
					XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
					factory.setNamespaceAware(true);
			        XmlPullParser xpp = factory.newPullParser();
			        xpp.setInput(httpConnection.getInputStream(), "ISO-8859-1");
			        
			        int eventType = xpp.getEventType();
			        
			        String labelString = null, operatorString = null, addressString = null, laneString = null, postalCodeString = null, provinceString = null,
			        	localityString = null, saleTypeString = null, sentTypeString = null, xCoordString = null, yCoordString = null, priceString = null,
			        	dateString = null, hourString = null;
			        
		        	while (eventType != XmlPullParser.END_DOCUMENT ){
		                String name = null;
		                switch (eventType){
		                	case XmlPullParser.START_TAG:
		                		name = xpp.getName();
		                		if (name.equalsIgnoreCase("Rotulo")){
		                			labelString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Operador")){
		                			operatorString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Direccion")){
		                			addressString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Margen")){
		                			laneString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("CPostal")){
		                			postalCodeString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Provincia")){
		                			provinceString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Localidad")){
		                			localityString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("TipoVenta")){
		                			saleTypeString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Remision")){
		                			sentTypeString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("CoordenadaX_dec")){
		                			xCoordString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("CoordenadaY_dec")){
		                			yCoordString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Precio")){
		                			priceString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Fecha")){
		                			dateString = xpp.nextText();
		                		} else if (name.equalsIgnoreCase("Hora")){
		                			hourString = xpp.nextText();
		                		}
		                		break;
		                	case XmlPullParser.END_TAG:
		                		name = xpp.getName();
		                		if (name.equalsIgnoreCase("estaciones_servicio_brief")){
		                			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm", Locale.getDefault());
		    						Date fecha = new GregorianCalendar(0, 0, 0).getTime();
		    						float price = 0.0f;
		    						try {
		    							fecha = sdf.parse(dateString + " " + hourString);
		    							NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
		    							price = (format.parse(priceString)).floatValue();
		    						} catch (ParseException e) {
		    							e.printStackTrace();
		    						}
		    						
		    						String referencia = xCoordString + yCoordString;
		    						frequencyUp(referencia);

		    						GasStation gasStation = new GasStation(labelString, operatorString, addressString,
		    								laneString,	postalCodeString, provinceString, localityString, fecha,
		    								saleTypeString,	sentTypeString, xCoordString, yCoordString, referencia, price);

		    						founds++;
		    						if(gasStation.getXkey() != null && !gasStation.getXkey().isEmpty()) {
		    							addNewGS(gasStation, String.valueOf(gasType), priceString);
		    							publishProgress(gasStation);
		    						}
		                		}
		                		break;
		                }
		                eventType = xpp.next();
			        }
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (DOMException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} finally {}
						
			Log.d(getClass().getName(), "END-refreshGSList");
			
			return founds;  
	    }
		

		@Override
	    protected void onProgressUpdate(GasStation... values) {

	    }
	
	    @Override
	    protected void onPostExecute(Integer founds) {
			if(founds == 0) {
				announceNewGasStation(new GasStation());
				Toast toast = Toast.makeText(getApplicationContext(), R.string.noResults_Stations, Toast.LENGTH_LONG);
				toast.show();
			}
			Intent intentLoading = new Intent(FINISHED_LOADING);
			Log.d(getClass().getName(), "sendBroadcast:" + FINISHED_LOADING);
			sendBroadcast(intentLoading);
	    	stopSelf();
	    }
	}

	public static List<GasStation> lookUpSynchronous(int gasType, String gasStationFeed, String gasTypeParamFeed, String bBOXParamFeed, String perimeterSearch) {
		List<GasStation> result = new ArrayList<GasStation>();
		URL url;
		
		try {
			String gasStationsLookupFeed = gasStationFeed;
			gasStationsLookupFeed += "&" + gasTypeParamFeed +  "=" + gasType;
			gasStationsLookupFeed += "&" + bBOXParamFeed +  "=" + perimeterSearch;
			
			url = new URL(gasStationsLookupFeed);
			
			URLConnection connection;
			connection = url.openConnection();

			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK) {
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				factory.setNamespaceAware(true);
		        XmlPullParser xpp = factory.newPullParser();
		        xpp.setInput(httpConnection.getInputStream(), "ISO-8859-1");
		        
		        int eventType = xpp.getEventType();
		        
		        String labelString = null, operatorString = null, addressString = null, laneString = null, postalCodeString = null, provinceString = null,
		        	localityString = null, saleTypeString = null, sentTypeString = null, xCoordString = null, yCoordString = null, priceString = null,
		        	dateString = null, hourString = null;
		        
	        	while (eventType != XmlPullParser.END_DOCUMENT ){
	                String name = null;
	                switch (eventType){
	                	case XmlPullParser.START_TAG:
	                		name = xpp.getName();
	                		if (name.equalsIgnoreCase("Rotulo")){
	                			labelString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Operador")){
	                			operatorString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Direccion")){
	                			addressString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Margen")){
	                			laneString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("CPostal")){
	                			postalCodeString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Provincia")){
	                			provinceString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Localidad")){
	                			localityString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("TipoVenta")){
	                			saleTypeString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Remision")){
	                			sentTypeString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("CoordenadaX_dec")){
	                			xCoordString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("CoordenadaY_dec")){
	                			yCoordString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Precio")){
	                			priceString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Fecha")){
	                			dateString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Hora")){
	                			hourString = xpp.nextText();
	                		}
	                		break;
	                	case XmlPullParser.END_TAG:
	                		name = xpp.getName();
	                		if (name.equalsIgnoreCase("estaciones_servicio_brief")){
	                			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm", Locale.getDefault());
	    						Date fecha = new GregorianCalendar(0, 0, 0).getTime();
	    						float price = 0.0f;
	    						try {
	    							fecha = sdf.parse(dateString + " " + hourString);
	    							NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
	    							price = (format.parse(priceString)).floatValue();
	    						} catch (ParseException e) {
	    							e.printStackTrace();
	    						}
	    						
	    						String referencia = xCoordString + yCoordString;

	    						GasStation gasStation = new GasStation(labelString, operatorString, addressString,
	    								laneString,	postalCodeString, provinceString, localityString, fecha,
	    								saleTypeString,	sentTypeString, xCoordString, yCoordString, referencia, price);
	    						
	    						result.add(gasStation);
	                		}
	                		break;
	                }
	                eventType = xpp.next();
		        }
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DOMException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} finally {}
		
		return result;  
	}
	
	public static List<GasStation> lookUpHtmlSynchronous(int gasType, String gasStationFeed, String gasTypeParamFeed, String locality, int maxItems) {
		List<GasStation> result = new ArrayList<GasStation>();
		URL url;
		InputStream in = null;
		
		try {
			String gasStationsLookupFeed = gasStationFeed + locality;
			gasStationsLookupFeed += "&" + gasTypeParamFeed +  "=" + gasType;
			
			url = new URL(gasStationsLookupFeed);
			Log.d("", "url cheapers" +  gasStationsLookupFeed);
			
			URLConnection connection;
			connection = url.openConnection();

			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK) {
				in =  httpConnection.getInputStream();
				InputStreamReader is = new InputStreamReader(in);
				StringBuilder sb = new StringBuilder();
				BufferedReader br = new BufferedReader(is);
				String read = br.readLine();

				while(read != null) {
				    sb.append(read);
				    read = br.readLine();
				}
				
				String cleanedHtml = "<gasStations>";
				int indexA, indexB;
				indexA = sb.toString().indexOf("<tr class=\"trWhite\">");
				indexB = sb.toString().indexOf("<td colspan=\"10\" class=\"tdPaginator\">");
				
				if(sb.toString() != null && !sb.toString().isEmpty() && indexA != -1 && indexB != -1)
					cleanedHtml += sb.toString().substring(indexA, indexB).trim();
				
				cleanedHtml += "</gasStations>";
				
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				factory.setNamespaceAware(true);
		        XmlPullParser xpp = factory.newPullParser();
		        xpp.setInput(new ByteArrayInputStream(cleanedHtml.getBytes()), "UTF-8");
		        
		        int eventType = xpp.getEventType();
		        
		        String labelString = null, operatorString = null, addressString = null, laneString = null, postalCodeString = null, provinceString = null,
		        	localityString = null, saleTypeString = null, sentTypeString = null, xCoordString = null, yCoordString = null, priceString = null,
		        	dateString = null;
		        boolean started = false;
	        	while (eventType != XmlPullParser.END_DOCUMENT ){
	                String name = null;
        			operatorString = "";
        			postalCodeString = "";
	                
	                switch (eventType){
	                	case XmlPullParser.START_TAG:
	                		name = xpp.getName();
	                		if (name.equalsIgnoreCase("tr") || started){
	                			started = true;
	                			if (name.equalsIgnoreCase("img")) {
	                				String[] coords = xpp.getAttributeValue("", "onClick").split(",");
	                				//onClick="centrar(-5.965194,37.370472,12)
	                				xCoordString = coords[0].replace("centrar(", "");
	                				yCoordString = coords[1];
	                			}
	                			if (name.equalsIgnoreCase("td")) {
	                				if(provinceString == null) {
	                					provinceString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(localityString == null) {
		                				localityString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(addressString == null) {
		                				addressString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(laneString == null) {
		                				laneString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(dateString == null) {
		                				dateString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(priceString == null) {
		                				priceString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(labelString == null) {
		                				labelString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(saleTypeString == null) {
		                				saleTypeString = xpp.nextText().trim();
	                					break;
	                				}
		                			if(sentTypeString == null) {
		                				sentTypeString = xpp.nextText().trim();
	                					break;
	                				}
	                			}	
	                		}
	                		break;
	                	case XmlPullParser.END_TAG:
	                		name = xpp.getName();
	             			
	                		if (name.equalsIgnoreCase("tr")){
	                			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
	    						Date fecha = new GregorianCalendar(0, 0, 0).getTime();
	    						float price = 0.0f;
	    						try {
	    							fecha = sdf.parse(dateString);
	    							NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
	    							price = (format.parse(priceString)).floatValue();
	    						} catch (ParseException e) {
	    							e.printStackTrace();
	    						}
	
	                			String referencia = xCoordString + yCoordString;
	
	    						GasStation gasStation = new GasStation(labelString, operatorString, addressString,
	    								laneString,	postalCodeString, provinceString, localityString, fecha,
	    								saleTypeString,	sentTypeString, xCoordString, yCoordString, referencia, price);
	    						
	    						result.add(gasStation);
	    						
	    						if(result.size() == maxItems) {
	    							return result;
	    						}
	                			provinceString = null;
	                			localityString = null;
	                			addressString = null;
	                			laneString = null;
	                			dateString = null;
	                			priceString = null;
	                			labelString = null; 
	                			saleTypeString = null;
	                			sentTypeString= null;
	                			xCoordString = null;
	                			yCoordString = null;
	                			started = false;
		                		break;
	                		}
	                }
	                eventType = xpp.next();
		        }

			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;  
	}
}
